import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import cm from 'classnames'
import { useRouter } from 'next/router'
import { hotSearchData } from '@/store'
import { useRecoilValue } from 'recoil'
import { goBack } from '@/utils/utils'

// 本地持久化已搜素过的关键字
const saveKeyword = word => {
  const keywords = JSON.parse(localStorage.getItem('keywords') || '[]')
  keywords.unshift(word)
  localStorage.setItem('keywords', JSON.stringify([...new Set(keywords)]))
}

const Index = () => {
  const router = useRouter()
  const topData = useRecoilValue(hotSearchData)
  const [searchArr, setSearchArr] = useState([])
  const [inputText, setText] = useState('')

  useEffect(() => {
    setSearchArr(JSON.parse(localStorage.getItem('keywords') || '[]'))
    return () => {
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  const toSearch = text => {
    if (router.pathname === '/search') {
      router.replace('/search?word=' + text)
    } else {
      router.push('/search?word=' + text)
    }
  }

  const toPlay = item => {
    if (item.label === '直播') {
      let url = `/live/${item.url ? item.url : ''}`
      if (router.pathname === '/live/[id]') {
        router.replace(url)
      } else {
        router.push(url)
      }
    } else {
      let url = `/vod/detail/${item.id}`
      if (router.pathname === '/vod/detail/[id]') {
        router.replace(url)
      } else {
        router.push(url)
      }
    }
  }

  const handleEvent = e => setText(e.currentTarget.value)
  const toSearchPage = () => {
    const text = inputText.trim()
    saveKeyword(text)
    if (text) {
      if (router.pathname === '/search') {
        router.replace('/search?word=' + text)
      } else {
        router.push('/search?word=' + text)
      }
    }
  }
  const keyDown = e => {
    e.keyCode === 13 && toSearchPage()
  }

  const clear = () => {
    setSearchArr([])
    localStorage.removeItem('keywords')
  }

  return (
    <div className={styles.search}>
      <div className={styles.topInput}>
        <div className={styles.back} onClick={goBack}>
          <img loading="lazy" src="/images/back.png" alt="返回" />
        </div>
        <div className={styles.inputBox}>
          <input type="text" placeholder="搜索" maxLength={20} onInput={handleEvent} onKeyUp={keyDown} />
          <img loading="lazy" className={styles.searchImg} src="/images/search.png" alt="搜索" onClick={toSearchPage} />
        </div>
      </div>

      <div className={styles.searchBox}>
        {searchArr.length ? (
          <>
            <div className={styles.menu}>
              <span>历史记录</span>
              <div className={styles.menuBtn} onClick={clear}>
                <span>删除</span>
                <img loading="lazy" alt="删除" src="/images/delete.png" />
              </div>
            </div>
            <div className={styles.searchList}>
              {searchArr.map(item => (
                <div className={styles.item} key={item} onClick={() => toSearch(item)}>
                  {item}
                </div>
              ))}
            </div>
          </>
        ) : null}
        {Array.isArray(topData) ? (
          <>
            <div className={styles.menu}>
              <span>热门搜索</span>
            </div>
            {topData.flat(1).map(item => {
              return (
                <div className={styles.hotSearch} key={item.index} onClick={() => toPlay(item)}>
                  <p
                    className={cm(styles.hotIndex, {
                      [styles.one]: item.index === 1,
                      [styles.two]: item.index === 2,
                      [styles.three]: item.index === 3
                    })}
                  >
                    {item.index}
                  </p>
                  <p className={cm(styles.hotName, 'textEllipsis')}>{item.name}</p>
                  {item.label ? (
                    <p className={cm(styles.hotLabel, item.label === '直播' ? styles.hotLabelLive : '')}>
                      {item.label}
                    </p>
                  ) : null}
                </div>
              )
            })}
          </>
        ) : null}
      </div>
    </div>
  )
}

export default Index

export async function getServerSideProps() {
  return {
    props: {
      layoutProps: {
        noSomeMetaInfo: false,
        title: '搜索页面',
        desc: ''
      }
    }
  }
}
